<script setup>
import { ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import ChannelSelect from '@/views/article/components/ChannelSelect.vue';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

const emit = defineEmits(['add-article', 'edit-article']);
const props = defineProps({
    options: {
        type: Array,
        required: true
    },
    editData: {
        type: Object,
        default: null
    }
});

const drawer = ref(false);
const formRef = ref(null);
const defaultForm = {
    title: '',
    cate_id: '',
    cover_img: '',
    content: ''
};
const formModel = ref({ ...defaultForm });
const imageUrl = ref('');

const open = (row = null) => {
    drawer.value = true;
    imageUrl.value = '';
    
    if (formRef.value) {
        formRef.value.clearValidate();
    }

    if (row?.id) {
        formModel.value = {
            id: row.id,
            title: row.title || '',
            cate_id: row.cate_name || '',
            cover_img: row.cover_img || '',
            content: row.content || ''
        };
        
        if (formModel.value.cover_img) {
            if (formModel.value.cover_img instanceof File) {
                imageUrl.value = URL.createObjectURL(formModel.value.cover_img);
            } else {
                imageUrl.value = formModel.value.cover_img;
            }
        }
    } else {
        formModel.value = { ...defaultForm };
        imageUrl.value = '';
    }

    nextTick(() => {
        const titleInput = document.querySelector('.el-drawer .el-input__inner');
        if (titleInput) titleInput.focus();
    });
};

const onSelectFile = (uploadFile) => {
    const file = uploadFile.raw;
    if (!file) return;

    const isImage = file.type.startsWith('image/');
    if (!isImage) {
        return ElMessage.error('只能上传图片文件（JPG、PNG等）');
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        return ElMessage.error('图片大小不能超过2MB');
    }

    imageUrl.value = URL.createObjectURL(file);
    formModel.value.cover_img = file;
};

const removeImage = () => {
    imageUrl.value = '';
    formModel.value.cover_img = '';
};

// 去掉表单验证逻辑，直接提交
const onPublish = (state) => {
    formModel.value.state = state;
    const newArticle = { ...formModel.value };
    
    const matchedCate = props.options.find(item => item.name === newArticle.cate_id);
    newArticle.cate_name = matchedCate ? matchedCate.name : '其他';
    newArticle.pub_date = new Date().toISOString().split('T')[0];

    if (!newArticle.id) {
        newArticle.id = Date.now();
        emit('add-article', newArticle);
        ElMessage.success(state === '已发布' ? '文章发布成功' : '文章存稿成功');
    } else {
        emit('edit-article', newArticle);
        ElMessage.success(state === '已发布' ? '文章编辑并发布成功' : '文章编辑并存稿成功');
    }

    drawer.value = false;
    formModel.value = { ...defaultForm };
    imageUrl.value = '';
};

defineExpose({ open });
</script>

<template>
    <el-drawer 
        v-model="drawer" 
        :title="formModel.id ? '编辑文章' : '添加文章'" 
        size="70%"
        destroy-on-close
    >
        <!-- 去掉表单的 :rules 验证规则 -->
        <el-form 
            :model="formModel" 
            ref="formRef" 
            label-width="80px"
        >
            <el-form-item label="文章标题">
                <el-input v-model="formModel.title" placeholder="请输入文章标题"></el-input>
            </el-form-item>
            
            <el-form-item label="文章分类">
                <ChannelSelect :options="options" v-model="formModel.cate_id"></ChannelSelect>
            </el-form-item>
            
            <el-form-item label="文章封面">
                <el-upload 
                    class="avatar-uploader" 
                    :show-file-list="false" 
                    :on-change="onSelectFile"
                    accept="image/*"
                    :auto-upload="false"
                >
                    <div class="upload-container">
                        <img 
                            v-if="imageUrl" 
                            :src="imageUrl" 
                            class="preview-img" 
                            alt="文章封面"
                        >
                        <el-icon v-else class="upload-plus-icon"><Plus /></el-icon>
                        <el-button 
                            v-if="imageUrl"
                            type="text" 
                            class="remove-btn" 
                            @click.stop="removeImage"
                        >
                            删除
                        </el-button>
                    </div>
                </el-upload>
                <div class="upload-hint">支持JPG、PNG格式，大小不超过2MB（完整显示无裁剪）</div>
            </el-form-item>
            
            <!-- 去掉文章内容的 prop 属性和验证 -->
            <el-form-item label="文章内容">
                <div class="editor-container">
                    <quill-editor 
                        v-model="formModel.content" 
                        content-type="html" 
                        theme="snow"
                        :options="{
                            placeholder: '请输入文章内容...',
                            modules: {
                                toolbar: [
                                    ['bold', 'italic', 'underline', 'strike'],
                                    [{ 'header': [1, 2, 3, false] }],
                                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                                    [{ 'align': [] }],
                                    ['link', 'image']
                                ]
                            }
                        }"
                    />
                </div>
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
                <el-button type="info" @click="onPublish('草稿')" style="margin-left: 10px;">存稿</el-button>
                <el-button @click="drawer = false" style="margin-left: 10px;">取消</el-button>
            </el-form-item>
        </el-form>      
    </el-drawer> 
</template>

<style scoped>
.upload-container {
  width: 200px;
  height: 150px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background-color: #f5f7fa;
  position: relative;
  overflow: hidden;
}

.upload-container:hover {
  border-color: #4096ff;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
  margin: 0 auto;
}

.upload-plus-icon {
  font-size: 24px;
  color: #86909c;
}

.remove-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 0;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-container:hover .remove-btn {
  opacity: 1;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #86909c;
}

.editor-container {
  width: 100%;
  min-height: 300px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

.el-form-item:last-child {
  margin-top: 20px;
}
</style>
